package security.internal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import security.Resource;

public class SecurityAuthoritiesHolderImpl extends HibernateDaoSupport
		implements SecurityAuthoritiesHolder {

	private Map<String, Map<String, String>> cache = new HashMap<String, Map<String, String>>();

	@SuppressWarnings("unchecked")
	private List<Resource> getResourcesByType(String resType) {
		return getHibernateTemplate().find("FROM Resource WHERE resType = ?",
				resType);

	}

	public Map<String, String> loadAuthorities(String resType) {
		Map<String, String> authorities = cache.get(resType);
		if (authorities == null) {
			authorities = new HashMap<String, String>();
			List<Resource> urlResources = getResourcesByType(resType);
			for (Resource resource : urlResources) {
				authorities.put(resource.getResString(),
						resource.getRoleAuthorities());
			}
			cache.put(resType, authorities);
		}

		return authorities;
	}

}
